/* $Id: ListBoxEditor.java 137 2011-08-29 20:33:36Z altdotua@gmail.com $ */

package alt.djudge.frontend.client.ui.editors;

import java.util.HashMap;
import java.util.Map;

import alt.djudge.frontend.shared.dto.admin.AdminDTOEntry;

import com.google.gwt.user.client.Window;
import com.google.gwt.user.client.rpc.AsyncCallback;
import com.google.gwt.user.client.ui.ListBox;


public class ListBoxEditor extends ListBox implements CustomEditor
{
	private Map<String, String> key2value = new HashMap<String, String>();
	
	private Map<String, String> value2key = new HashMap<String, String>();
	
	final int keyField;
	
	final int valueField;
	
	public ListBoxEditor(final int keyField, final int valueField)
	{
		this.keyField = keyField;
		this.valueField = valueField;
	}
	
	public AsyncCallback<AdminDTOEntry[]> getCallback()
	{
		return new AsyncCallback<AdminDTOEntry[]>()
		{
			
			@Override
			public void onSuccess(AdminDTOEntry[] result)
			{
				onDataLoaded(result);
			}
			
			@Override
			public void onFailure(Throwable caught)
			{
				Window.alert(caught.toString());
			}
		};
	}
	
	private void onDataLoaded(AdminDTOEntry[] data)
	{
		String dummyValue = "<none>";
		addItem(dummyValue);
		key2value.put("0", dummyValue);
		value2key.put(dummyValue, "0");
		for (AdminDTOEntry entry : data)
		{
			String key = entry.getFieldValue(keyField);
			String value = entry.getFieldValue(valueField);
			addItem(value);
			key2value.put(key, value);
			value2key.put(value, key);
		}
	}
	
	@Override
	public String getValueForKey(String key)
	{
		return key2value.get(key);
	}

	@Override
	public String getKey()
	{
		return value2key.get(getValue());
	}

	@Override
	public void setKey(String key)
	{
		String valueForKey = key2value.get(key);
		setValue(valueForKey);
	}

	@Override
	public void setValue(String value)
	{
		for (int i = 0; i < super.getItemCount(); i++)
			if (super.getItemText(i).equals(value))
				setSelectedIndex(i);
	}

	@Override
	public String getValue()
	{
		return super.getValue(super.getSelectedIndex()); 
	}
}
